// 水面涟漪效果
Shader "PJD/Scerne/Ripples"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _RippleScale("RippleScale",Range(1,5)) = 2
        _TimeScale("TimeScale",Range(0.1,3)) = 1
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100
        
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag


            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
                float3 worldPos : TEXCOORD1;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float _RippleScale;
            float _TimeScale;
            #define PI 3.141592653

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                o.worldPos = mul(unity_ObjectToWorld,v.vertex);
                return o;
            }


            float3 CaculationRipple(float2 uv,float time)
            {
                float4 ripple = tex2D(_MainTex,uv);
                // gb 类似高度 0~1 转到 -1~1 
                ripple.gb = ripple.gb * 2 - 1;
                // a 通道获取波纹的时间
                float dropFrac = frac(ripple.a + time);
                // r 通道相当于波纹的大小(也可以理解为波纹的时间限制)
                float timeFace = dropFrac - 1 + ripple.r;
                // 淡出效果处理
                float dropFactor = 1 - saturate(dropFrac);
                // 计算最终的高度，用一个sin计算出随时间的振幅，修改一下值就知道什么效果了
                float final = dropFrac * sin(clamp(timeFace * 9.0,0,4.0) * PI);
                return float3(ripple.rg * final ,0.5);
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // fixed dis = distance(fixed2(0.5,0.5),i.uv);
                // fixed p = 1 - dis;
                // p = p - sin(_Time.y * _Range);
                // p = frac(p);
                // return p;

                fixed3 ripple = CaculationRipple(i.uv/_RippleScale,_Time.y * _TimeScale);
               
                fixed3 lightDir = fixed3(0,1,0);//normalize(_WorldSpaceCameraPos.xyz - i.worldPos);
                fixed3 normalDir =  UnpackNormal(fixed4(ripple,1)).xyz;  //normalize(ripple);
                float NdotL = dot(normalDir,lightDir);
                return NdotL;
            }
            ENDCG
        }
    }
}
